import React, { useEffect, useMemo, useRef, useState } from 'react'
import style from './Index.module.less'
import logo from '@img/robot.png'
import { PlusOutlined } from '@ant-design/icons'
import classNames from 'classnames'
import { Button, Empty, Input, message, Skeleton } from 'antd'
import { sendRequest, getListRequest, getDetailRequest } from './ajax'
import { awaitWrap, formatDate } from '@src/assets/js/tool'
import $ from 'jquery'

async function sendHandle (ref, lastid, title, setLoading, setAnswering, setVersion, setCurrentId, setCurrentTitle, setListVersion) {
  setLoading(true)
  setAnswering(true)
  setTimeout(() => {
    const c = ref.current
    if (c !== null) {
      $(c).animate({ scrollTop: c.scrollHeight })
    }
  }, 0)
  const [e, d] = await awaitWrap(sendRequest(title, lastid))
  setLoading(false)
  setListVersion(Date.now())
  if (e !== null) {
    setAnswering(false)
    message.error(e.message)
  }
  if (e === null && d !== null) {
    if (lastid === '') {
      setCurrentId(d.sessionid)
      setCurrentTitle(title)
    }
    setVersion(Date.now())
  }
}

async function getList (setList, setListLoading) {
  setListLoading(true)
  const [e, d] = await awaitWrap(getListRequest())
  setListLoading(false)
  if (e === null && d !== null) {
    setList(d)
  }
}

async function initDetail (ref, id, setDetail, setAnswering, setLoading, setContent) {
  setLoading(true)
  const [e, d] = await awaitWrap(getDetailRequest(id))
  setLoading(false)
  setAnswering(false)
  setContent('')
  if (e === null && d !== null) {
    setDetail(d)
    setTimeout(() => {
      const c = ref.current
      if (c !== null) {
        $(c).animate({ scrollTop: c.scrollHeight })
      }
    }, 0)
  }
}

function dealAnswer (t) {
  const s = t.replace(/\n/g, '<br />').replace(/\\n/g, '<br />')
  const l = s.split('<br />').filter(li => li)
  return (
    <>
      {l.map((li, i) => {
        return (
          <p key={i}>{li}</p>
        )
      })}
    </>
  )
}

function Main () {
  const containerRef = useRef(null)
  const [content, setContent] = useState('')
  const [sending, setSending] = useState(false)
  const [answering, setAnswering] = useState(false)
  const [list, setList] = useState([])
  const [currentId, setCurrentId] = useState('')
  const [currentTitle, setCurrentTitle] = useState('')
  const [detail, setDetail] = useState(null)
  const [version, setVersion] = useState(Date.now())
  const [listVersion, setListVersion] = useState(Date.now())
  const [loading, setLoading] = useState(false)
  const [listLoading, setListLoading] = useState(false)
  const message = useMemo(() => {
    if (detail !== null) {
      return detail.message
    }
    return []
  }, [detail])
  const lastid = useMemo(() => {
    if (message.length > 0) {
      return message[message.length - 1].sessionid
    }
    return ''
  }, [message])
  useEffect(() => {
    getList(setList, setListLoading).then(null, null)
  }, [listVersion])
  useEffect(() => {
    if (currentId !== '') {
      initDetail(containerRef, currentId, setDetail, setAnswering, setLoading, setContent).then(null, null)
    }
  }, [containerRef, currentId, version])
  return (
    <div className={style.container}>
      <div className={style.inner}>
        <div className={style.left}>
          <div className={style['left-header']}>
            <img src={logo} className={style.logo} />
            <span>DS智能聊天</span>
          </div>
          <a className={style['left-add']} onClick={() => { setCurrentId(''); setCurrentTitle(''); setDetail(null) }}>
            <PlusOutlined />
            <span className={style['left-add-text']}>新建聊天</span>
          </a>
          <div className={style['left-list']}>
            <div className={style['left-list-inner']}>
              {
                listLoading && list.length === 0 && (
                  <div className={style['list-loading']}>
                    <Skeleton active />
                  </div>
                )
              }
              {
                list.map(li => (
                  <a
                    key={li.id} className={classNames(style['left-li'], { [style.active]: currentId === li.id })} onClick={() => {
                      if (currentId !== li.id) {
                        setDetail(null)
                        setCurrentId(li.id)
                        setCurrentTitle(li.title)
                      }
                    }}
                  >
                    <div className={style['left-li-title']}>{decodeURIComponent(li.title)}</div>
                    <div className={style['left-li-date']}>{formatDate(li.update_datetime)}</div>
                  </a>
                ))
              }
            </div>
          </div>
        </div>
        <div className={style.right}>
          <div className={style['right-header']}>
            {currentTitle !== '' ? decodeURIComponent(currentTitle) : '新建聊天'}
          </div>
          <div className={style['right-content']} ref={containerRef}>
            {
              loading && detail === null && !answering && (
                <Skeleton active />
              )
            }
            {
              message.length === 0 && !loading && !sending && (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
              )
            }
            {
              message.map((li, i) => {
                return (
                  <div key={i} className={style['message-block']}>
                    <div className={style['right-item']}>
                      <div className={style['right-item-icon']}>我</div>
                      <div className={style['right-item-content']}>{decodeURIComponent(li.title)}</div>
                    </div>
                    <div className={style['right-item']}>
                      <div className={style['right-item-robot']}>
                        <img src={logo} />
                      </div>
                      <div className={style['right-item-content']}>
                        {dealAnswer(li.answer)}
                      </div>
                    </div>
                  </div>
                )
              })
            }
            {
              answering && (
                <div className={style['message-block']}>
                  <div className={style['right-item']}>
                    <div className={style['right-item-icon']}>我</div>
                    <div className={style['right-item-content']}>{content}</div>
                  </div>
                  <div className={style['right-item']}>
                    <div className={style['right-item-robot']}>
                      <img src={logo} />
                    </div>
                    <div className={style['right-item-content']}>
                      <div className={style['answer-dot']} />
                    </div>
                  </div>
                </div>
              )
            }
          </div>
          <div className={style['right-input-block']}>
            <Input.TextArea className={style['right-input']} placeholder='请输入' autoSize={false} value={content} onChange={e => setContent(e.target.value)} disabled={sending} />
            <Button
              type='primary' className={style['send-btn']} loading={sending} onClick={() => {
                sendHandle(containerRef, lastid, content, setSending, setAnswering, setVersion, setCurrentId, setCurrentTitle, setListVersion).then(null, null)
              }}
            >发送
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Main
